package com.ng.finance.api.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ng.finance.api.entity.BxVoucher;
import com.ng.finance.api.entity.UserPay;
import com.ng.finance.api.mapper.BxVoucherMapper;
import com.ng.finance.api.service.BxVoucherService;
import com.ng.finance.api.service.UserPayService;
import com.ng.finance.common.constant.ResultCode;
import com.ng.finance.common.pojo.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 83673
 * @since 2018-11-05
 */
@Service
public class BxVoucherServiceImpl extends ServiceImpl<BxVoucherMapper, BxVoucher> implements BxVoucherService {

    @Resource
    UserPayService userPayService;


    @Override
    public Result selectBxVoucher(Long id) {
        BxVoucher bxVoucher = baseMapper.selectOne(new BxVoucher(id));
        return Result.build(ResultCode.SUCCESS, bxVoucher);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result goBx(Long id, String bxPic) {
        //查询报销单是否存在
        BxVoucher bxVoucher = baseMapper.selectOne(new BxVoucher(id));
        if (ObjectUtils.isEmpty(bxVoucher)) {
            return Result.build(ResultCode.FORBIDDEN, "报销单不存在");
        }
        //更新消费列表
        List<String> ids = Arrays.asList(bxVoucher.getBxId().split(";"));
        List<UserPay> list = new ArrayList<>();
        ids.forEach(p ->
                list.add(new UserPay(p, 4))
        );
        boolean batchById = userPayService.updateBatchById(list);
        //更新报销单状态
        Integer integer = baseMapper.updateBxVoucher(id, bxPic);
        if (integer <= 0 || !batchById) {
            throw new RuntimeException("操作失败!");
        }


        return Result.build(ResultCode.SUCCESS, "操作成功");
    }

    @Override
    public Result selectBxVoucherList(Integer bxTag, Long userId, Page page) {
        List<BxVoucher> bxVouchers = baseMapper.selectBxVoucherList(bxTag, userId, page);
        Map<String, Object> map = new HashMap<>();
        page.setRecords(bxVouchers);
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());
        map.put("pages", page.getPages());

        map.put("current", page.getCurrent());
        return Result.build(ResultCode.SUCCESS, map);

    }
}
